<?php

namespace app\api\controller\mycurrency;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\LeaseConfig;
use app\common\model\mycurrency\LeaseDeposit as Deposit;
use app\common\model\mycurrency\OperateDistributionMoneylog;
use app\common\model\mycurrency\OperateDistributionUser;
use app\common\model\mycurrency\UserMoneyLog;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;

/**
 * 租赁 - 押金接口
 */
class LeaseDeposit extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $agent = null;


    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 押金支付 下单
     */
    public function placeanorder(){
        //添加订单
        $deposit = Deposit::depositAdd($this->auth->id);
        if(!$deposit){
            $this->error('充值记录添加失败');
        }
        $this->success('充值记录添加成功',[
            'deposit_id' => $deposit->id,
        ]);
    }

    /**
     * 押金支付 - 余额支付
     */
    public function balancePayment(){
        $param = $this->request->param();
        $rule = [
            ['deposit_id', 'require', '押金支付记录id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $deposit = Deposit::where(['id' => $param['deposit_id'],'user_id' => $this->auth->id,'deletetime' => null])->find();
        if(!$deposit){
            $this->error('充值记录不存在');
        }
        if($deposit['status'] != Deposit::STATUS_WEIZHIFU){
            $this->error('充值记录非待支付状态');
        }
        $user = \app\common\model\User::get($this->auth->id);
//        if($user->money < $deposit['amount']){
//            $this->error('余额不足');
//        }
        $distribution_user = OperateDistributionUser::where(['user_id' => $user->id])->find();
        if($distribution_user->money < $deposit['amount']){
            $this->error('余额不足');
        }

        Db::startTrans();
        try {
            //扣除用户余额
//            UserMoneyLog::moneyChange($user->id,$deposit['amount'],UserMoneyLog::TYPE_ZHIFUYAJIN,[
//                'memo' => '支付租赁订单押金',
//                'lease_deposit_id' => $deposit->id,
//            ]);
            //扣除用户分销余额
            OperateDistributionMoneylog::moneyChange($distribution_user->id,$deposit['amount'],OperateDistributionMoneylog::TYPE_YAJINZHIFU,[
                'memo' => '支付租赁订单押金',
                'lease_deposit_id' => $deposit->id,
            ]);
            //处理押金充值支付成功后逻辑
            Deposit::paymentSuccess($deposit->id,Deposit::PAY_TYPE_YUE);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付成功');
    }


    /**
     * 查询押金支付状态
     */
    public function queryInfo(){
        $param = $this->request->param();
        $rule = [
            ['deposit_id', 'require', '押金支付记录id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $deposit = Deposit::where(['id' => $param['deposit_id'],'user_id' => $this->auth->id,'deletetime' => null])->find();
        if(!$deposit){
            $this->error('充值记录不存在');
        }
        $this->success('查询成功',$deposit);
    }

    /**
     * 押金支付记录
     */
    public function depositList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
            ['status',"require|in:1,2", '查询类型不能为空|查询类型错误'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'user_id' => $this->auth->id,
            'deletetime' => null,
        ];
        if($params['status'] == 1){//查询已经支付还没有退款的押金
            $where['status'] = Deposit::STATUS_YIZHIFU;
        }else if($params['status'] == 2){//查询体现的 包括 以体现及体现中的
            $where['status'] = ['in',[Deposit::STATUS_YITUIKUAN,Deposit::STATUS_TUIKUANGZHONG]];
        }
        $list = Deposit::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        $num = Deposit::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 申请退押金
     */
    public function depositRefund(){
        $params = $this->request->param();
        $rule = [
            ['deposit_id', 'require', '押金充值记录id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $deposit = Deposit::where(['id' => $params['deposit_id'],'deletetime' => null])->find();

        Db::startTrans();
        try {
            \app\common\model\mycurrency\LeaseDeposit::depositRefund($deposit->id);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($deposit->pay_type == Deposit::PAY_TYPE_WECHAT || $deposit->pay_type == Deposit::PAY_TYPE_ALIPAY){//押金支付方式 微信or支付宝
            $this->success('退款中');
        }elseif ($deposit->pay_type == Deposit::PAY_TYPE_YUE){//余额支付
            $this->success('退款成功');
        }

    }

}
